import type { Router } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { startProgress, stopProgress } from '@vben/utils';

import { accessRoutes, coreRouteNames } from '#/router/routes';
import { useAuthStore } from '#/store';

import { generateAccess } from './access';
import { $t } from '#/locales';
import { routerFindAllApi } from '#/api/object/router'
import type { TreeProps } from 'ant-design-vue';

/**
 * 通用守卫配置
 * @param router
 */
function setupCommonGuard(router: Router) {
  // 记录已经加载的页面
  const loadedPaths = new Set<string>();

  router.beforeEach(async (to) => {
    to.meta.loaded = loadedPaths.has(to.path);

    // 页面加载进度条
    if (!to.meta.loaded && preferences.transition.progress) {
      startProgress();
    }
    return true;
  });

  router.afterEach((to) => {
    // 记录页面是否加载,如果已经加载，后续的页面切换动画等效果不在重复执行

    loadedPaths.add(to.path);

    // 关闭页面加载进度条
    if (preferences.transition.progress) {
      stopProgress();
    }
  });
}

/**
 * 权限访问守卫配置
 * @param router
 */
function setupAccessGuard(router: Router) {
  router.beforeEach(async (to, from) => {
    const accessStore = useAccessStore();
    const userStore = useUserStore();
    const authStore = useAuthStore();

    // 基本路由，这些路由不需要进入权限拦截
    if (coreRouteNames.includes(to.name as string)) {
      if (to.path === LOGIN_PATH && accessStore.accessToken) {
        return decodeURIComponent(
          (to.query?.redirect as string) ||
          userStore.userInfo?.homePath ||
          DEFAULT_HOME_PATH,
        );
      }
      return true;
    }

    // accessToken 检查
    if (!accessStore.accessToken) {
      // 明确声明忽略权限访问权限，则可以访问
      if (to.meta.ignoreAccess) {
        return true;
      }

      // 没有访问权限，跳转登录页面
      if (to.fullPath !== LOGIN_PATH) {
        return {
          path: LOGIN_PATH,
          query:
            to.fullPath === DEFAULT_HOME_PATH
              ? {}
              : { redirect: encodeURIComponent(to.fullPath) },
          replace: true,
        };
      }
      return to;
    }

    // 生成路由表
    // 当前登录用户拥有的角色标识列表
    const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());

    // 如果已经检查过权限并生成了路由，直接放行

    if (accessStore.isAccessChecked) {
      return true;
    }

    try {
      // 👇 新增：调用接口获取菜单数据
      const rees = await routerFindAllApi();
      const backendMenus = rees.data;

      // console.log('【接口返回菜单】', backendMenus);

      // 👇 新增：将后端菜单结构转换为前端 treeData 格式
      const convertToTreeData = (menus: any[]): TreeProps[] => {
        return menus.map(menu => ({
          ...menu,
          meta: {
            icon: '',
            title: $t(`${menu.meta.locale}`),
          },
          key:String(menu.id),
          name: $t(`${menu.meta.locale}`),
          children: menu.children ? convertToTreeData(menu.children) : undefined,
        }));
      };

      const accessibleMenus = convertToTreeData(backendMenus);
      // console.log('【转换后的菜单】', accessibleMenus);

      // 👇 新增：根据菜单生成可访问的路由（这里你可以按需做权限过滤）
      const accessibleRoutes = await generateAccess({
        roles: [],
        router,
        routes: accessRoutes,
        menus: backendMenus, // 可传入菜单用于匹配生成路由
      });

      // 👇 新增：保存菜单信息和路由信息
      accessStore.setAccessMenus(accessibleMenus); // 用于左侧菜单显示
      accessStore.setAccessRoutes(accessibleRoutes); // 用于添加动态路由
      accessStore.setIsAccessChecked(true);


      if (Array.isArray(accessibleRoutes.accessibleRoutes)) {
        accessibleRoutes.accessibleRoutes.forEach((route) => {
          router.addRoute(route);
        });
      } else {
        console.error('【错误】生成的 accessibleRoutes 不是一个数组');
      }

      // 👇 新增：重定向到目标路径
      const redirectPath = (from.query.redirect ??
        (to.path === DEFAULT_HOME_PATH
          ? DEFAULT_HOME_PATH
          : to.fullPath)) as string;

      return {
        ...router.resolve(decodeURIComponent(redirectPath)),
        replace: true,
      };
    } catch (error) {
      console.error('【权限初始化失败】', error);
      return {
        path: '/500',
        replace: true,
      };
    }
  });
}

/**
 * 项目守卫配置
 * @param router
 */
function createRouterGuard(router: Router) {
  /** 通用 */
  setupCommonGuard(router);
  /** 权限访问 */
  setupAccessGuard(router);
}

export { createRouterGuard };
